package keyfun.display 
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	/**
	 * ...
	 * @author Key Hui
	 */
	public class ScrollView extends Sprite
	{
		private var isMoving:Boolean = false;
		private var bg:Sprite = new Sprite();
		private var maskSp:Sprite = new Sprite();
		private var lastX:Number = 0;
		private var lastY:Number = 0;
		
		public function ScrollView(targetWidth:Number = 800, targetHeight:Number = 600) 
		{
			
			bg.graphics.beginFill(0xDDDDDD, 1);
			bg.graphics.drawRect(0, 0, targetWidth, targetHeight);
			bg.graphics.endFill();
			addChild(bg);
			
			maskSp.graphics.beginFill(0xDDDDDD, 1);
			maskSp.graphics.drawRect(0, 0, targetWidth, targetHeight);
			maskSp.graphics.endFill();
			addChild(maskSp);
			this.mask = maskSp;
			
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event = null):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			this.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDownHandler);
		}
		
		private function onMouseDownHandler(e:MouseEvent):void
		{
			if (!isMoving)
			{
				isMoving = true;
				this.addEventListener(Event.ENTER_FRAME, onEnterFrameHandler);
				this.addEventListener(MouseEvent.MOUSE_UP, onMouseUpHandler);
				this.addEventListener(MouseEvent.ROLL_OUT, onMouseUpHandler);
				
				lastX = stage.mouseX;
				lastY = stage.mouseY;
			}
		}
		
		private function onEnterFrameHandler(e:Event):void
		{
			if (isMoving)
			{
				var offsetX:Number = stage.mouseX - lastX;
				var offsetY:Number = stage.mouseY - lastY;
				for (var i:int = 2; i < this.numChildren; i++)
				{
					var child:DisplayObject = this.getChildAt(i);
					child.x += offsetX;
					child.y += offsetY;
					checkBoundary(child);
				}
			}
		}
		
		private function checkBoundary(child:DisplayObject):void
		{
			if (child.x < 0)
			{
				child.x = 0;
			}
			else if (child.x > mask.width - child.width)
			{
				child.x = mask.width - child.width;
			}
			
			if (child.y > 0)
			{
				child.y = 0;
			}
			else if (child.y < mask.height - child.height)
			{
				child.y = mask.height - child.height;
			}
		}
		
		private function onMouseUpHandler(e:MouseEvent):void
		{
			this.removeEventListener(Event.ENTER_FRAME, onEnterFrameHandler);
			this.removeEventListener(MouseEvent.MOUSE_UP, onMouseUpHandler);
			this.removeEventListener(MouseEvent.ROLL_OUT, onMouseUpHandler);
			isMoving = false;
		}

	}

}